package student.aistar.service.impl;

import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Service;
import student.aistar.mapper.TVSeckillMapper;
import student.aistar.model.entity.Orders;
import student.aistar.model.entity.WebSeckill;
import student.aistar.service.ITVSeckillService;

import java.nio.channels.Channel;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 本类用来演示:
 *
 * @author: qinFeng
 * @date: 2021/10/11 20:53
 */
@Service
public class TVSeckillServiceImpl implements ITVSeckillService {
    @Autowired
    TVSeckillMapper tvSeckillMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 查询没有开始秒杀的商品
     * @return
     */
    @Override
    public List<Map<String, Object>> beforeActive() {
        return tvSeckillMapper.beforeActive();
    }

    /**
     * 更新时间到达秒杀范围内的商品状态为 1
     */
    @Override
    public void updateState() {
        tvSeckillMapper.updateState();
    }

    /**
     * 找到秒杀商品的id
     * @return
     */
    @Override
    public List<Long> findKillId() {
        return tvSeckillMapper.findKillId();
    }

    /**
     * 将结束秒杀的商品状态设置为2
     */
    @Override
    public void endActive() {
        tvSeckillMapper.endActive();
    }

    /**
     * 找到过期的商品id
     * @return
     */
    @Override
    public List<Long> findEndId() {
        return tvSeckillMapper.findEndId();
    }

    /**
     * 获取当前秒杀id的状态, 也就是用户抢购商品的状态
     * @param killId
     * @return
     */
    @Override
    public String getStateByKillId(Integer killId) {
        String state = (String) redisTemplate.opsForValue().get("st_" + killId);
        if(state == null)
            state = "2";
        return state;
    }


    /**
     * 产生订单信息放入到队列中
     */
    //@RabbitListener(queuesToDeclare = @Queue("spikeOrderQueue"))
    @Override
    public void generateSpikeOrder(Integer userId, Integer killId) {
        Map<String, Integer> map = new HashMap<>();
        map.put("userId", userId);
        map.put("killId", killId);
        rabbitTemplate.convertAndSend("spikeOrderQueue", map);
    }

    @Override
    public int insertOrders(Orders order) {
        return tvSeckillMapper.insertOrders(order);
    }

    @Override
    public void insertOrderDetail(Integer orderId) {
        tvSeckillMapper.insertOrderDetail(orderId);
    }

    @Override
    public WebSeckill getSeckillTime(Integer productId) {
        return tvSeckillMapper.getStartTimeNow(productId);
    }


}
